package com.lvmama.rhino.web.sso;

import com.lvmama.rhino.base.CookieUtil;
import com.lvmama.rhino.base.HttpClientUtil;
import com.lvmama.rhino.base.SSOTokenUtil;
import com.lvmama.rhino.utils.RhinoConstant;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * sso自定义过滤器
 */
public class SSOFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String token = request.getParameter("token");
            RhinoConstant rhinoConstant = RhinoConstant.getInstance();
            String ssoServiceUrl = rhinoConstant.getValue("ssoServiceUrl");
            String tokenValidateUrl = rhinoConstant.getValue("tokenValidateUrl");
            if (null == token) {
                Cookie cookie = CookieUtil.getCookieByName(request, "token");
                if (null != cookie) {
                    token = cookie.getValue();
                }
            }
            if (null == token) {
                //没有token，重定向至sso server登录页
                tokenExpiredRedirect(request, response, ssoServiceUrl);
            } else {
                String urlString = request.getRequestURI();
                if (urlString.endsWith("/logout")) {
                    String JedisUrl = rhinoConstant.getValue("JedisUrl");
                    String JedisPort = rhinoConstant.getValue("JedisPort");
                    Jedis jedis = new Jedis(JedisUrl, Integer.parseInt(JedisPort));
                    jedis.del(token.getBytes());
                    jedis.close();
                    SecurityUtils.getSubject().logout();
                    response.sendRedirect(ssoServiceUrl);//重定向至sso server登录页
                    return;
                }

                //有token,去sso server验证token的有效性
                Map<String, String> map = new HashMap<>();
                map.put("token", token);
                String result = HttpClientUtil.doGet(tokenValidateUrl, map);
                if (StringUtils.isNotBlank(result)) {//验证成功，跳转至首页，并从redis中获取权限
                    SystemSession.setUser(SSOTokenUtil.getToken(request));//设置系统session
                    Cookie cookie = new Cookie("token", token);
                    cookie.setPath("/rhino");
                    response.addCookie(cookie);
                    filterChain.doFilter(request, response);
                } else {
                    //验证失败，重定向至sso server登录页
                    tokenExpiredRedirect(request, response, ssoServiceUrl);
                }
            }
        }
    }

    /**
     * token失效处理
     *
     * @param request       request
     * @param ssoServiceUrl 跳转路径
     */
    private void tokenExpiredRedirect(HttpServletRequest request, HttpServletResponse response, String ssoServiceUrl) throws IOException, ServletException {
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(header);
        if (isAjax) {
            // 处理ajax请求
            //回写数据
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("timeout", true);
            jsonObj.put("redirectUrl", ssoServiceUrl);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(jsonObj.toString());
        }else{
            response.sendRedirect(ssoServiceUrl);
        }
    }

    public void destroy() {

    }
}
